import { fileURLToPath, URL } from 'node:url';

import { ConfigEnv, defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import UnoCSS from 'unocss/vite';
import vueJsx from '@vitejs/plugin-vue-jsx';
import Components from 'unplugin-vue-components/vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import { ArcoResolver } from 'unplugin-vue-components/resolvers';
import { vitePluginForArco } from '@arco-plugins/vite-vue';
import eslintPlugin from '@nabla/vite-plugin-eslint';
import AutoImport from 'unplugin-auto-import/vite';

export default defineConfig((configEnv: ConfigEnv) => {
	const env = loadEnv(configEnv.mode, process.cwd());
	return {
		// base: VITE_PUBLIC_PATH,
		plugins: [
			vue(),
			vueJsx(),
			eslintPlugin({
				eslintOptions: {
					cache: true,
					fix: true,
					overrideConfigFile: 'eslint.config.ts',
					cacheLocation: 'node_modules/.cache/.eslint-cache',
				},
			}),
			UnoCSS(),

			AutoImport({
				include: [
					/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
					/\.vue$/,
					/\.vue\?vue/, // .vue
				],
				dirs: ['./src'],
				imports: [
					'vue',
					'vue-router',
					{
						'@/hooks/useCache': ['useCache'],
						'@/hooks/useMessage': ['useMessage'],
					},
				],
				dts: 'src/types/auto-import.d.ts',
			}),

			Components({
				dts: 'src/types/components.d.ts',
				resolvers: [
					ArcoResolver({
						sideEffect: true,
					}),
				],
			}),
			vitePluginForArco({
				style: 'css',
			}),
			createHtmlPlugin({
				inject: {
					data: {
						title: env.VITE_GLOB_APP_TITLE,
					},
				},
			}),
		],
		esbuild: {
			pure: env.VITE_DROP_CONSOLE === 'true' ? ['console.log', 'debugger'] : [],
		},
		resolve: {
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url)),
			},
		},
		server: {
			port: Number(env.VITE_PORT) || 9999,
			host: '0.0.0.0',
			proxy: {
				'/admin-api': {
					target: 'http://192.168.10.200:18080/admin-api',
					// target: 'http://rakwcw.ipx.dhjdd.cn:6080/admin-api/',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/admin-api/, ''),
				},
				'/im/ws': {
					target: 'ws://192.168.10.200:18080', // WebSocket 目标地址
					ws: true, // 启用 WebSocket 代理
					changeOrigin: true, // 改变源
					rewrite: (path) => path.replace(/^\/admin-api/, ''),
				},
			},
		},
	};
});
